<?php

namespace app\api\controller;

use app\api\library\SantoSms;
use app\common\controller\Api;
use app\common\library\Email;
use think\Db;
use think\Exception;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    /**
     * 手机号+验证码一键登录
     */
    public function other_new_login()
    {
        $phone = trim($this->request->post('phone',''));
        $code = $this->request->post('code');
        if(!$phone){
            $this->error('信息不完整');
        }
        //查询是否已经注册
        $member = Db::name('yl_member')->where(['phone' => $phone])->find();
        Db::startTrans();
        try {
            //验证码判断
            $sms_where = [
                'event' => 'login',
                'mobile' => $phone,
                'code' => $code,
                'status' => 0,
            ];
            $sms = Db::name('sms')->where($sms_where)->find();
            if (empty($sms)){
                $this->error('验证码不正确');
            }else {
                Db::name('sms')->where($sms_where)->update(['status'=>1]);
            }
            //注册判断
            if (empty($member)){
                //如果为空，则需要注册
                $salt = GetRandStr(4,0);
                $token = md5($phone.$salt);
                $insert_data = [
                    'create_time'=>time(),
                    'code'=>GetRandStr(),
                    'token'=>$token,
                    'phone'=>$phone,

                ];
                Db::name('yl_member')->insertGetId($insert_data);

            }
            $member = Db::name('yl_member')->where(['phone' => $phone])->find();
            //登录
            if ($member['status'] != 1) {
                $this->error('account un login');
            }

            // 登入设备已上限
            $ip = $this->request->ip();
            $ips = Db::name('yl_member')->where('ip',$ip)->select();
            $m_ids = $ips?array_column($ips,'member_id'):[];
            if(CC('ip_login_limit') > 0 && count($m_ids) > CC('ip_login_limit') && !in_array($member['id'],$m_ids)){
                $this->error('登录限制');
            }
            //更新登录信息
            $re = Db::name('yl_member')->where('phone',$phone)->update([
                'login_time'=>time(),
                'ip'=>$this->request->ip()
            ]);

            //登录日志
            if($re){
                Db::name('yl_login_log')->insert([
                    'member_id'=>$member['id'],
                    'name'=>$phone,
                    'create_time'=>time(),
                    //'device'=>$device,
                    'ip'=>$this->request->ip(),
                ]);
            }
            // 如果所有操作都成功，提交事务
            Db::commit();
        }catch (Exception $e){
            // 如果有任何一个操作失败，回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('successful',['token'=> $member['token']]);

    }


    // 注册用户
    public function reg(){
        //用户账号
        $user = trim($this->request->post('user',''));
        //邮箱
        //$email = trim($this->request->post('email',''));
        // 验证码
        //$code = trim($this->request->post('code',''));
        //密码
        $password = trim($this->request->post('password',''));
        //安全密码
        //$security_password = trim($this->request->post('security_password',''));
        //区号
        //$phone_ex = trim($this->request->post('phone_ex',''));
        //手机号
        //$phone = trim($this->request->post('phone',''));
        //邀请码
        //$invite_code = trim($this->request->post('invite_code',''));

        if (!$user || !$password) {
            $this->error('信息不完整');
        }
//        // 验证码验证
//        $where = [];
//        $where['event'] = 'reg';
//        $where['mobile'] = $email;
//        $where['code'] = $code;
//        $where['status'] = 0;
//        $sms = Db::name('sms')->where($where)->find();
//        if (!$sms) {
//            $this->error('code error');
//        }
//        // 验证邮箱是否重复
//        $member = Db::name('yl_member')->where('email', $email)->find();
//        if ($member) {
//            $this->error('email register');
//        }
//        // 验证手机号重复
//        if ($phone) {
//            $member = Db::name('yl_member')->where('phone', $phone)->find();
//            if ($member) {
//                $this->error('phone register');
//            }
//        }

         //验证用户名重复
        if ($user) {
            $member = Db::name('yl_member')->where('user', $user)->find();
            if ($member) {
                $this->error('user register');
            }
        }

        $salt = GetRandStr(4,0);
        $token = md5($user.$salt);
        $insert_data = [
            'user' => $user,
//            'email'=>$email,
            'password'=>md5($password),
//            'security_password'=>md5($security_password),
            'create_time'=>time(),
            'code'=>GetRandStr(),
            'token'=>$token,
//            'phone_ex'=>$phone_ex,
//            'phone'=>$phone,
        ];
//        // 验证邀请码
//        if ($invite_code) {
//            $share_member = Db::name('yl_member')->where('code', $invite_code)->find();
//            if (!$share_member) {
//                $this->error('invitecode error');
//            }
//            $insert_data['share_id'] = $share_member['id'];
//            $insert_data['combination'] = $share_member['combination']?$share_member['combination'].$share_member['id'].'-':'-'.$share_member['id'].'-';
//        }

        $re = Db::name('yl_member')->insert($insert_data);
        if($re){
            $this->success('successful',['token'=>$token]);
        }else{
            $this->error('失败');
        }
    }

    // 登录
    public function login(){
        //$code = trim($this->request->post('code',''));
        $user = trim($this->request->post('user',''));
        $pass = trim($this->request->post('password',''));
        //$device = trim($this->request->post('device',''));
        if(!$user || !$pass /*|| !$code*/){
            $this->error('信息不完整');
        }
//		$captcha = new Captcha();
        /*$code_data = Db::name('yl_code')->where('code',$code)->find();
        if($code_data){
            Db::name('yl_code')->where('id',$code_data['id'])->delete();
        }else{
            $this->error('code error');
        }*/
//		if(!$captcha->check($code,'')){
////			$this->error('code error');
//		}
        $users = Db::name('yl_member')->where('user',$user)->find();
        if(empty($users)){
            $this->error('账户注销');
        } else if ($users['status'] != 1) {
            $this->error('该账户不能登录');
        } else if($users['password'] != md5($pass)){
            Db::name('yl_login_log')->insert([
                'member_id'=>$users['id'],
                'name'=>$users['user'],
                'create_time'=>time(),
                'type'=>1,
                //'device'=>$device,
                'ip'=>$this->request->ip(),
            ]);
            $this->error('密码错误');
        }

        // 登入设备已上限
        $ip = $this->request->ip();
        $ips = Db::name('yl_member')->where('ip',$ip)->select();
        $m_ids = $ips?array_column($ips,'member_id'):[];
        if(CC('ip_login_limit') > 0 && count($m_ids) > CC('ip_login_limit') && !in_array($users['id'],$m_ids)){
            $this->error('登录限制');
        }

        Db::name('yl_member')->where('user',$user)->update([
            'login_time'=>time(),
            'ip'=>$this->request->ip()
        ]);
        Db::name('yl_login_log')->insert([
            'member_id'=>$users['id'],
            'name'=>$users['user'],
            'create_time'=>time(),
            //'device'=>$device,
            'ip'=>$this->request->ip(),
        ]);
        $this->success('successful',['token'=>$users['token']]);
    }

    // 发送短信（发送验证码）
    public function send_sms(){
        $phone_ex = str_replace('+', '', $this->request->post('phone_ex'));
        $phone = $this->request->post('phone');
        $event = $this->request->post('event');
        $ip = $this->request->ip();
        //限制发送次数
        $timestamp = strtotime(date('Y-m-d')); // 获取今天的零点时间戳
        if($event != "login"){
            //手机号次数
            $mobile_sms = Db::name('sms')
                ->where('event',$event)
                ->where('mobile',$phone)
                ->where('createtime','>',$timestamp)
                ->count();
            if ($mobile_sms > 4){
                $this->error('今日该号码已经到达发送次数');
            }
            //ip次数
            $ip_sms = Db::name('sms')
                ->where('event',$event)
                ->where('ip',$ip)
                ->where('createtime','>',$timestamp)
                ->count();
            if ($ip_sms > 4){
                $this->error('今日该号码的ip已经到达发送次数');
            }
        }

        $statusStr = array(
            "0" => "短信发送成功",
            "-1" => "参数不全",
            "-2" => "服务器空间不支持",
            "30" => "密码错误",
            "40" => "账号不存在",
            "41" => "余额不足",
            "42" => "帐户已过期",
            "43" => "IP地址限制",
            "50" => "内容含有敏感词"
        );

        $user = CC('sms_user'); //短信平台帐号
        $pass = CC('sms_password');//md5(CC('sms_password')); //短信平台密码
        $code = rand(10000,99999);
        $content="[".CC('sms_qm')."]您的验证码是:{".$code."}。如非本人操作，请忽略本短信";//要发送的短信内容

        $sendphone = $phone;
        if ($phone_ex != '86') {
            $sendphone = $phone_ex.$sendphone;
        }

        // 验证手机号
        if ($event == 'forget' || $event == 'oldphone' || $event == 'paypass' || $event == 'pass') {
            $flag = Db::name('yl_member')->where('phone', $phone)->find();
            if (!$flag) {
                $this->error('phone empty');
            }
        } else if ($event == 'newphone' || $event == 'register') {
            $newmember = Db::name('yl_member')->where('phone', $phone)->find();
            if ($newmember) {
                $this->error('phone register');
            }
        }

        $url = "https://api.smsbao.com/sms?u={$user}&p={$pass}&m={$sendphone}&c=".urlencode($content);
        $result = file_get_contents($url);
//        $result = 0;

        /*$smsID = SantoSms::send($user, $pass, $phone_ex.$phone, $content);
        $smsID = 1;*/
        if($result == 0){ // 发送成功
            Db::name('sms')->insert([
                'event'=>$event,
                'mobile'=>$phone,
                'code'=>$code,
                'ip'=>$ip,
                'createtime'=>time()
            ]);
            $this->success('send successful', ['code' => $code]);
        }else{
            $this->error('send fail');
        }
    }

    // 发送邮件（验证码）
    public function send_email(){
        $event = $this->request->post('event','');
        $email = $this->request->post('email','');
        if (!$event || !$email) {
            $this->error('incomplete information');
        }
        if (!preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/', $email)) {
            $this->error('邮箱格式错误');
        }
        $email_model = new Email();
        $code = rand(10000,99999);
        $content="[".CC('sms_qm')."]您的验证码是".$code;//要发送的短信内容
        //$res=$email_model->subject('验证码')->to($email)->message($content)->send();
        $res = true;
        if($res!==false){
            Db::name('sms')->insert([
                'event'=>$event,
                'mobile'=>$email,
                'code'=>$code,
                'ip'=>$this->request->ip(),
                'createtime'=>time()
            ]);
            $this->success('send successful', ['code' => $code]);
        }else{
            $this->error(__('return fail').':'.$email_model->getError(),$email_model->getError());
        }
    }

    //
    public function vip_config_list()
    {
        $result = Db::name('yl_vip_config')->select();
        $this->success('successful',$result);

    }

    //爬取接口数据
    public function paqu_jiekou($url,$data,$type)
    {
        //初始化cURL会话
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if (!empty($data)){
            //携带请求参数
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        if ($type == "pdd"){
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/x-www-form-urlencoded;charset=utf-8'
            ));
        }elseif ($type == "dd"){
        }else{
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Accept: application/json',
            ));
        }
        //使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请求
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        //停止cURL验证对端证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        //1.检查SSL对端证书中是否存在通用名称。(已弃用)
        //2.检查公共名称的存在，并验证它是否与所提供的主机名匹配。0表示不检查名称。在生产环境中，该选项的值应该保持为2(默认值)。
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        //将curl_exec()获取的信息以文件流的形式返回，而不是直接输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //执行cURL会话
        $response = curl_exec($ch);
        // 检查是否有错误发生
        if (curl_errno($ch)) {
            return curl_error($ch);
        }
        //关闭cURL会话
        curl_close($ch);
        $data = json_decode($response, true);
        //历史信息
        return $data;
    }

    /**
     * 拼多多
     */
    //商品列表接口
    public function goods_list()
    {
        // 替换为你的接口地址
        $url = 'http://host:port/api/router';

        // 替换为你的应用信息和访问令牌
        $clientId = 'your client id';
        $accessToken = 'your access token';
        $client_secret = $this->request->param('client_secret');

        // 设置请求参数
        $data = array(
            'created_at_from' => 1654012800,//	模版id
            'goods_name' => 'str',//商品名称模糊查询,outer_id,is_onsale,goods_name三选一，优先级is_onsale>outer_id>goods_name
            'outer_goods_id' => '1',//商家外部商品编码，支持多个，用逗号隔开，最多10个
//            'sign' => 'your sign',//API输入参数签名结果，签名算法参考开放平台接入指南第三部分底部。***
            'type' => 'pdd.goods.list.get',//API接口名称
            'is_onsale' => 1,//上下架状态，0-下架，1-上架,outer_id,is_onsale,goods_name三选一，优先级is_onsale>outer_id>goods_name
            'outer_id' => 'str',
            'client_id' => 'your client id',//POP分配给应用的client_id ***
            'access_token' => 'your access token',//通过code获取的access_token ***
            'data_type' => 'JSON',//响应格式，即返回数据的格式，JSON或者XML（二选一），默认JSON，注意是大写
            'created_at_end' => 1654099200,
            'page' => 1,
            'cost_template_id' => 1,
            'page_size' => 100,
            'timestamp' => 1527065024,//UNIX时间戳，单位秒，需要与拼多多服务器时间差值在10分钟内
        );
        //获取sign
        $sign = $this->get_sign($data,$client_secret);
        $data['sign'] = $sign;
        $response =  $this->paqu_jiekou($url,$data,"pdd");

        $goods_list = $response['goods_list'];
        $data_pdds = [];
        $data_pddss = [];
        $data_pdd_sku = [];
        $data_pdd_sku_spec = [];

        //
        foreach ($goods_list as $goods_item)
        {
            //商品
            $goods_pdds_item = [];
            //$goods_pdds_item[] = $goods_item['created_at'];
            $goods_pdds_item['goods_id'] = $goods_item['goods_id'];
            $goods_pdds_item['goods_name'] = $goods_item['goods_name'];
            $goods_pdds_item['quantity'] = $goods_item['goods_quantity'];

            //商品预扣库存
            $goods_pdds_item['reserve_quantity'] = $goods_item['goods_reserve_quantity'];
            $goods_pdds_item['image_url'] = $goods_item['image_url'];
            $goods_pdds_item['thumb_url'] = $goods_item['thumb_url'];
            $goods_pdds_item['status'] = $goods_item['is_onsale'];
            if ($goods_item['is_onsale'] == 0){
                $goods_pdds_item['status'] = 2;
            }
            $data_pdds[] = $goods_pdds_item;
            //sku表
            $goods_pdd_sku_item = [];
            foreach ($goods_item['sku_list'] as $sku_item){
                $goods_pdd_sku_item['is_onsale'] = $sku_item['is_sku_onsale'];
                $goods_pdd_sku_item['outer_goods_id'] = $sku_item['outer_goods_id'];
                $goods_pdd_sku_item['outer_id'] = $sku_item['outer_id'];
                $goods_pdd_sku_item['reserve_quantity'] = $sku_item['reserve_quantity'];
                $goods_pdd_sku_item['sku_id'] = $sku_item['sku_id'];
                $goods_pdd_sku_item['quantity'] = $sku_item['sku_quantity'];
                $goods_pdd_sku_item['spec'] = $sku_item['spec'];
                $goods_pdd_sku_item['goods_id'] = $sku_item['goods_id'];

                $data_pdd_sku[] = $goods_pdd_sku_item;

                //spec表
                $goods_pdd_sku_spec_item = [];
                foreach ($sku_item['spec_details'] as $spec_details)
                {
                    $goods_pdd_sku_spec_item['parent_id'] = $spec_details['parent_id'];
                    $goods_pdd_sku_spec_item['parent_name'] = $spec_details['parent_name'];
                    $goods_pdd_sku_spec_item['spec_id'] = $spec_details['spec_id'];
                    $goods_pdd_sku_spec_item['spec_name'] = $spec_details['spec_name'];
                    $goods_pdd_sku_spec_item['spec_note'] = $spec_details['spec_note'];

                    $data_pdd_sku_spec[] = $goods_pdd_sku_spec_item;
                }
            }


        }
        Db::startTrans();
        try {
            //总商品
            Db::name('pdds')->insertAll($data_pdds);
            //sku
            Db::name('pdd_sku')->insertAll($data_pdd_sku);
            //spec
            Db::name('pdd_spec')->insertAll($data_pdd_sku_spec);

            //要商品
            Db::name('pddss')->insertAll($data_pddss);
            // 如果所有操作都成功，提交事务
            Db::commit();
        }catch (Exception $e){
            // 如果有任何一个操作失败，回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('successful',$response);
    }

    //商品分类
    public function goods_cates()
    {
        $url = 'http://host:port/api/router';
        $access_token = $this->request->param('access_token');
        $clientId = $this->request->param('clientId');
        $client_secret = $this->request->param('client_secret');
        // 设置请求参数
        $data = array(
            'access_token' => $access_token,
            'data_type' => 'JSON',
            'parent_cat_id' => 0,
            'type' => 'pdd.goods.cats.get',
            'client_id' => $clientId,
            'timestamp' => 1527065024,
        );
        //获取sign
        $sign = $this->get_sign($data,$client_secret);
        $data['sign'] = $sign;
        $response = $this->paqu_jiekou($url,$data,"pdd");
        $data_cate = [];
        $data_cate_item = [];
        foreach ($response['goods_cats_list'] as $goods_cats_list)
        {
            $data_cate_item['cat_id'] = $goods_cats_list['cat_id'];
            $data_cate_item['cat_name'] = $goods_cats_list['cat_name'];
            $data_cate_item['level'] = $goods_cats_list['level'];
            $data_cate_item['parent_cat_id'] = $goods_cats_list['parent_cat_id'];
            $data_cate[] = $data_cate_item;
        }
        $result = Db::name('pdd_cate')->insertAll($data_cate);
        if (empty($result)){
            $this->error('拼多多批量导入失败');
        }
        $this->success('successful');
    }

    //商品详情接口
    public function goods_info($goods_id,$accessToken,$clientId,$client_secret)
    {
        // 替换为你的接口地址
        $url = 'http://host:port/api/router';
        // 替换为你的应用信息和访问令牌
//        $clientId = 'your client id';
//        $accessToken = 'your access token';

        // 设置请求参数
        $data = array(
            'access_token' => $accessToken,
            'data_type' => 'JSON',
            'goods_id' => $goods_id,
            'type' => 'pdd.goods.information.get',
            'client_id' => $clientId,
            'timestamp' => 1527065024,
        );
        //获取sign
        $sign = $this->get_sign($data,$client_secret);
        $data['sign'] = $sign;
        $response =  $this->paqu_jiekou("pdd",$url,$data);
        return $response;
        $this->success('successful',$response);
    }
    //运费
    public function goods_template($template_id,$accessToken,$clientId,$client_secret)
    {
        // 替换为你的接口地址
        $url = 'http://host:port/api/router';
        // 设置请求参数
        $data = array(
            'access_token' => $accessToken,
            'data_type' => 'JSON',
            'template_id' => $template_id,
            'type' => 'pdd.goods.logistics.ser.template.detail',
            'client_id' => $clientId,
            'timestamp' => 1527065024,
        );
        //获取sign
        $sign = $this->get_sign($data,$client_secret);
        $data['sign'] = $sign;
        $response =  $this->paqu_jiekou("pdd",$url,$data);
        return $response;
    }

    //sign签名计算
    public function get_sign($data,$client_secret){
        // 按照首字母先后顺序排列参数
        ksort($data);
        // 拼接参数名+参数值
        $concatenatedString = '';
        foreach ($data as $key => $value) {
            $concatenatedString .= $key . $value;
        }
        // 首尾拼接client_secret并进行md5加密转大写
        $sign = strtoupper(md5($client_secret . $concatenatedString . $client_secret));
        return $sign;

    }


    //要的商品
    public function goodss_list()
    {
        // 替换为你的接口地址
        $url = 'http://host:port/api/router';

        // 替换为你的应用信息和访问令牌
        $clientId = 'your client id';
        $accessToken = 'your access token';

        $access_token = $this->request->param('access_token');
        $clientId = $this->request->param('clientId');
        $sign = $this->request->param('sign');
        $client_secret = $this->request->param('client_secret');

        // 设置请求参数
        $data = array(
            'created_at_from' => 1654012800,//	模版id
            'goods_name' => 'str',//商品名称模糊查询,outer_id,is_onsale,goods_name三选一，优先级is_onsale>outer_id>goods_name
            'outer_goods_id' => '1',//商家外部商品编码，支持多个，用逗号隔开，最多10个
            'type' => 'pdd.goods.list.get',//API接口名称
            'is_onsale' => 1,//上下架状态，0-下架，1-上架,outer_id,is_onsale,goods_name三选一，优先级is_onsale>outer_id>goods_name
            'outer_id' => 'str',
            'client_id' => $clientId,
//            'client_id' => 'your client id',//POP分配给应用的client_id ***
            'access_token' => $access_token,
//            'access_token' => 'your access token',//通过code获取的access_token ***
            'data_type' => 'JSON',//响应格式，即返回数据的格式，JSON或者XML（二选一），默认JSON，注意是大写
            'created_at_end' => 1654099200,
            'page' => 1,
            'cost_template_id' => 1,
            'page_size' => 100,
            'timestamp' => 1527065024,//UNIX时间戳，单位秒，需要与拼多多服务器时间差值在10分钟内
        );
        //获取sign
        $sign = $this->get_sign($data,$client_secret);
        $data['sign'] = $sign;
        $response =  $this->paqu_jiekou($url,$data,"pdd");
        $goodss_list = $response['goods_list'];
        $data_pddss = [];

        //
        foreach ($goodss_list as $goods_item)
        {
            //商品详情
            $goods_info = $this->goods_info($goods_item,$accessToken,$clientId,$client_secret);
            //运费详情
            $template_info = $this->goods_template($goods_info['cost_template_id'],$accessToken,$clientId,$client_secret);
            //
            $goods_pdds_value = [];
            //商品编码
            $goods_pdds_value['goods_id'] = $goods_item['goods_id'];
            //商品主图
            $goods_pdds_value['image_url'] = $goods_item['image_url'];
            //标题
            $goods_pdds_value['title'] = $goods_item['goods_name'];
            //商品总销量
            $goods_pdds_value['sales_num'] = 0;
            //价格
            $price = $goods_info['sku_list'][0]['price'];
            $price = bcmul($price,0.01,2);
            $goods_pdds_value['price'] = $price;
            //劵后价
            $goods_pdds_value['coupons_price'] = $price;
            //总评价
            $goods_pdds_value['evaluation'] = 0.00;
            //24小时销量
            $goods_pdds_value['sales24_num'] = 0;
            //运费
            if (!empty($template_info['list'][0]['value'])){
                $template_price = $template_info['list'][0]['value'];
            }elseif(!empty($template_info['list'][0]['content'][0]['price'])) {
                $template_price = $template_info['list'][0]['content'][0]['price'];
            }else{
                $template_price = 0;
            }
            $template_price = bcmul($template_price,0.01,2);
            $goods_pdds_value['freight'] = $template_price;
            //好评率*
            //$goods_pdds_value['positive_review_rate'] = $goods_item['goods_id'];
            //上架时间
            $goods_pdds_value['listing_time'] = $goods_item['created_at'];
//            //店铺名称*
//            $goods_pdds_value['shop_name'] = $goods_item['goods_id'];
//            //店铺商品数*
//            $goods_pdds_value['shop_goods_num'] = $goods_item['goods_id'];
//            //店铺评分*
//            $goods_pdds_value['shop_rating'] = $goods_item['goods_id'];
            //分类
            $pdd_info = Db::name('pdd_cate')->where('cat_id',$goods_info['cat_id'])->find();
            if (!empty($pdd_info)){
                $goods_pdds_value['cate_id'] = $pdd_info['id'];
            }
//            $goods_pdds_value['cate1_id'] = $goods_item['goods_id'];
//            $goods_pdds_value['cate2_id'] = $goods_item['goods_id'];
//            $goods_pdds_value['cate3_id'] = $goods_item['goods_id'];
//            $goods_pdds_value['cate4_id'] = $goods_item['goods_id'];
            $data_pddss[] = $goods_pdds_value;
        }
        Db::name('pddss')->insertAll($data_pddss);
    }

    /**
     * 抖店
     * 注意：需要相应的sdk
     */
    //商品列表
    public function products_list()
    {
        //curl版
        // 替换为你的实际应用密钥和访问令牌
//        $appKey = 'your_appkey_here';
//        $accessToken = 'your_accesstoken_here';
        $appKey = $this->request->param('appKey');
        $accessToken = $this->request->param('accessToken');
//        $sign = $this->request->param('sign');
        $appSecret = $this->request->param('appSecret');

        // 构造请求参数
        $params = [
            'app_key' => $appKey,                        // 应用密钥
            'method' => '',                              // API 方法，需要根据实际情况填写
            'access_token' => $accessToken,              // 访问令牌
            'param_json' => '{}',                        // 请求参数的 JSON 字符串，这里为空对象 {}
            'timestamp' => '2018-06-19 16:06:59',       // 时间戳，表示请求的时间
            'v' => '2',                                  // API 版本
        ];

        // 生成签名，需要根据实际情况使用合适的签名算法
//        $sign = 'your_sign_here';
        $paramPattern = 'app_key'.$appKey.'method'.'product.getCategories'.'param_json'.'{cid:12,page:1}'.'timestamp'.'2018-06-19 16:06:59'.'v'.'2';
        $signPattern = $appSecret.$paramPattern.$appSecret;
        $sign = hash_hmac("sha256", $signPattern, $appSecret);
        $params['sign'] = $sign;

        // 构造请求 URL
        $requestUrl = 'https://openapi-fxg.jinritemai.com?' . http_build_query($params);

        // 发送请求
        $response = file_get_contents($requestUrl);



        //php版(需要相应的sdk)

//        $request = new ProductListV2Request();
//        $param = new ProductListV2Param();
//        $request->setParam($param);
//        $param->status = 0;//(否)商品在店铺中状态: 0-在线；1-下线；2-删除；详见商品状态机
//        $param->check_status = 3;//(否)商品审核状态: 1-未提交；2-待审核；3-审核通过；4-审核未通过；5-封禁；7-审核通过待上架；详见商品状态机
//        $param->product_type = 0;//(否)商品类型；0-普通；1-新客商品；3-虚拟；6-玉石闪购；7-云闪购 ；127-其他类型；
//        $param->start_time = 1619161933;//(否)商品创建开始时间
//        $param->end_time = 1619162000;//(否)商品创建结束时间
//        $param->update_start_time = 1619161933;//(否)商品更新开始时间
//        $param->update_end_time = 1619161933;//(否)商品更新结束时间
//        $param->page = 1;//(是)页码，从1开始，最大为100；page* size最大不能超过1万条
//        $param->size = 100;//(是)页数，填写范围1~100；page* size最大不能超过1万条
//        $param->store_id = 123456;//(否)小时达商家使用的门店id
//        $param->name = "标题";//(否)商品标题，支持模糊匹配
//        $param->product_id = 3600137140018749665;//(否)商品id，最大支持传入100个；
//        //是否使用游标，true 使用，false 不使用；
//        //使用游标能遍历全量商品，不会受到只能查询到10000个数据的影响。
//        //特别说明：使用游标查询时，page字段失效，只会查询当前游标后面size条数据；
//        //根据获取查询数据为空来判断本次遍历结束；查询过程中数据发生变更，可能重复、遗漏数据；需要保证每次查询的筛选条件一致。
//        $param->use_cursor = true;//(否)游标
//        //游标id，结合use_cursor使用（use_cursor=true）;
//        //首次查询时不需要传值，每次查询结果会返回cursor_id，下一次查询时复制给该字段。当查询返回数据为空时，结束遍历。
//        $param->cursor_id = "WzE2ODI1Nzc4MjksMTc2NDMxMDczMDU3MDg0M10=";//(否)游标id
//        $param->can_combine_product = true;//(否)能否参加搭配
//        $response = $request->execute(accessToken);

        // 处理响应
        if ($response !== false) {
            $responseData = json_decode($response, true);
            if ($responseData) {
                // 处理 API 响应数据
                $data_dd = [];
                $data_dd_item = [];
                foreach ($responseData['data'] as $item)
                {
                    $data_dd_item['name_suffix'] = $item['name_suffix'];
                    $data_dd_item['name_prefix'] = $item['name_prefix'];
                    $data_dd_item['sell_num'] = $item['sell_num'];
                    $data_dd_item['can_not_combine_reason'] = $item['can_not_combine_reason'];
                    $data_dd_item['can_combine'] = 0;
                    if ($item['can_combine'] == true){
                        $data_dd_item['can_combine'] = 1;
                    }
                    $data_dd_item['product_id'] = $item['product_id'];
                    $data_dd_item['status'] = $item['status'];
                    $data_dd_item['check_status'] = $item['check_status'];
                    $data_dd_item['img'] = $item['img'];
                    $data_dd_item['name'] = $item['name'];
                    $data_dd_item['product_type'] = $item['product_type'];
                    $data_dd_item['spec_id'] = $item['spec_id'];
                    $data_dd_item['create_time'] = $item['create_time'];
                    $data_dd_item['update_time'] = $item['update_time'];
                    $data_dd_item['description'] = $item['description'];
                    $data_dd_item['extra'] = $item['extra'];
                    $data_dd_item['outer_product_id'] = $item['outer_product_id'];
                    if ($item['is_package_product'] == true){
                        $data_dd_item['is_sub_product'] = 1;
                    }elseif ($item['is_package_product'] == false){
                        $data_dd_item['is_sub_product'] = 0;
                    }
                    $data_dd[] = $data_dd_item;


                    $this->products_detail_info($item['product_id'],$appKey,$accessToken,$appSecret);
                    //
                    $goods_pdds_value = [];
                    //商品编码
                    $goods_pdds_value['goods_id'] = $item['product_id'];
                    //商品主图
                    $goods_pdds_value['image_url'] = $item['img'];
                    //标题
                    $goods_pdds_value['title'] = $item['name'];
                    //商品总销量
                    $goods_pdds_value['sales_num'] = $item['sell_num'];
                    //价格*
                    $goods_pdds_value['price'] = $item['goods_id'];
                    //劵后价*
                    $goods_pdds_value['coupons_price'] = $item['goods_id'];
                    //总评价*
                    $goods_pdds_value['evaluation'] = $item['goods_id'];
                    //24小时销量*
                    $goods_pdds_value['sales24_num'] = $item['goods_id'];
                    //运费*
                    $goods_pdds_value['freight'] = $item['goods_id'];
                    //好评率*
                    $goods_pdds_value['positive_review_rate'] = $item['goods_id'];
                    //上架时间
                    $goods_pdds_value['listing_time'] = $item['create_time'];
//                    //店铺名称*
//                    $goods_pdds_value['shop_name'] = $item['goods_id'];
//                    //店铺商品数*
//                    $goods_pdds_value['shop_goods_num'] = $item['goods_id'];
//                    //店铺评分*
//                    $goods_pdds_value['shop_rating'] = $item['goods_id'];
                    //分类
                    $goods_pdds_value['cate1_id'] = $item['category_detail']['first_cid'];
                    $goods_pdds_value['cate2_id'] = $item['category_detail']['second_cid'];
                    $goods_pdds_value['cate3_id'] = $item['category_detail']['third_cid'];
                    $goods_pdds_value['cate4_id'] = $item['category_detail']['fourth_cid'];
                }
                Db::startTrans();
                try {
                    Db::name('dds')->insertAll($data_dd);
//                    Db::name('')
                    // 如果所有操作都成功，提交事务
                    Db::commit();
                }catch (Exception $e){
                    // 如果有任何一个操作失败，回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }

            } else {
                $this->error('响应中的无效JSON');
            }
        } else {
            $this->error('发送请求错误');
        }
        $this->success('successful');
    }

    //抖店分类
    public function products_cate_list()
    {
        //curl版
        $appKey = $this->request->param('appKey');
        $accessToken = $this->request->param('accessToken');
        $sign = $this->request->param('sign');
        $appSecret = $this->request->param('appSecret');
        // 替换为你的实际应用密钥和访问令牌
//        $appKey = 'your_appkey_here';
//        $accessToken = 'your_accesstoken_here';
        // 构造请求参数
        $params = [
            'app_key' => $appKey,
            'method' => 'product.getCategories',
            'access_token' => $accessToken,
            'param_json' => '{cid:12,page:1}',
            'timestamp' => '2018-06-19 16:06:59',
            'v' => '2',
        ];
        // 生成签名，这里需要根据实际情况使用合适的签名算法
        $paramPattern = 'app_key'.$appKey.'method'.'product.getCategories'.'param_json'.'{cid:12,page:1}'.'timestamp'.'2018-06-19 16:06:59'.'v'.'2';
        $signPattern = $appSecret.$paramPattern.$appSecret;
        $sign = hash_hmac("sha256", $signPattern, $appSecret);
//        $sign = 'your_sign_here';
        $params['sign'] = $sign;
        // 构造请求 URL
        $requestUrl = 'https://openapi-fxg.jinritemai.com/product/getCategories?' . http_build_query($params);
        // 发送请求
        $response = file_get_contents($requestUrl);


        //php版(需要相应的sdk)

//        $request = new ProductGetCategoriesRequest();
//        $param = new ProductGetCategoriesParam();
//        $request->setParam($param);
//        $param->id = 0;
//        $response = $request->execute(accessToken);

        // 处理响应
        if ($response !== false) {
            $responseData = json_decode($response, true);
            if ($responseData) {
                // 处理 API 响应数据
                $data_dd_cate = [];
                $data_dd_cate_item = [];
                foreach ($responseData['data'] as $item)
                {
                    $data_dd_cate_item['id'] = $item['id'];
                    $data_dd_cate_item['name'] = $item['name'];
                    $data_dd_cate_item['level'] = $item['level'];
                    $data_dd_cate_item['level'] = $item['level'];
                    $data_dd_cate_item['parent_id'] = $item['parent_id'];
                    $data_dd_cate_item['is_leaf'] = $item['is_leaf'];
                    $data_dd_cate[] = $data_dd_cate_item;
                }
                $result = Db::name('category')->insertAll($data_dd_cate);
                if (empty($result)){
                    $this->error('分类导入失败');
                }
            } else {
                $this->error('响应中的无效JSON');
            }
        } else {
            $this->error('发送请求错误');
        }
        $this->success('successful');
    }

    //抖店详情
    public function products_detail_info($product_id,$appKey,$accessToken,$appSecret)
    {
        //curl版
        // 替换为你的实际应用密钥和访问令牌
        // 构造请求参数
        $params = [
            'app_key' => $appKey,
            'method' => 'product.detail',
            'access_token' => $accessToken,
            'param_json' => '{cid:12,page:1}',
            'timestamp' => '2018-06-19 16:06:59',
            'v' => '2',
        ];
        // 生成签名，这里需要根据实际情况使用合适的签名算法
        $paramPattern = 'app_key'.$appKey.'method'.'product.getCategories'.'param_json'.'{cid:12,page:1}'.'timestamp'.'2018-06-19 16:06:59'.'v'.'2';
        $signPattern = $appSecret.$paramPattern.$appSecret;
        $sign = hash_hmac("sha256", $signPattern, $appSecret);
        $params['sign'] = $sign;
        $params['product_id'] = $product_id;
        // 构造请求 URL
        $requestUrl = 'https://openapi-fxg.jinritemai.com/product/getCategories?' . http_build_query($params);
        // 发送请求
        $response = file_get_contents($requestUrl);


        //php版(需要相应的sdk)

//        $request = new ProductDetailRequest();
//        $param = new ProductDetailParam();
//        $request->setParam($param);
//        $param->product_id = "3558192687276554544";
//        $param->out_product_id = "dy001";
//        $param->show_draft = "false";
//        $param->store_id = 1111420330;
//        $response = $request->execute(accessToken);

        // 处理响应
        if ($response !== false) {
            $responseData = json_decode($response, true);
            if ($responseData) {
                // 处理 API 响应数据
                return $responseData;
            } else {
                $this->error('响应中的无效JSON');
            }
        } else {
            $this->error('发送请求错误');
        }
    }

    //运费
    public function yunfei_info($freight_id,$appKey,$accessToken,$appSecret)
    {
        //curl版
        // 替换为你的实际应用密钥和访问令牌
        // 构造请求参数
        $params = [
            'app_key' => $appKey,
            'method' => 'freightTemplate.detail',
            'access_token' => $accessToken,
            'param_json' => '{cid:12,page:1}',
            'timestamp' => '2018-06-19 16:06:59',
            'v' => '2',
        ];
        // 生成签名，这里需要根据实际情况使用合适的签名算法
        $paramPattern = 'app_key'.$appKey.'method'.'product.getCategories'.'param_json'.'{cid:12,page:1}'.'timestamp'.'2018-06-19 16:06:59'.'v'.'2';
        $signPattern = $appSecret.$paramPattern.$appSecret;
        $sign = hash_hmac("sha256", $signPattern, $appSecret);
        $params['sign'] = $sign;
        $params['freight_id'] = $freight_id;
        // 构造请求 URL
        $requestUrl = 'https://openapi-fxg.jinritemai.com/freightTemplate/detail?' . http_build_query($params);
        // 发送请求
        $response = file_get_contents($requestUrl);
        // 处理响应
        if ($response !== false) {
            $responseData = json_decode($response, true);
            if ($responseData) {
                // 处理 API 响应数据
                return $responseData;
            } else {
                $this->error('响应中的无效JSON');
            }
        } else {
            $this->error('发送请求错误');
        }
    }

    //门店
    public function store_info($store_id,$appKey,$accessToken,$appSecret)
    {
        //curl版
        // 替换为你的实际应用密钥和访问令牌
        // 构造请求参数
        $params = [
            'app_key' => $appKey,
            'method' => 'shop.getStoreDetail',
            'access_token' => $accessToken,
            'param_json' => '{cid:12,page:1}',
            'timestamp' => '2018-06-19 16:06:59',
            'v' => '2',
        ];
        // 生成签名，这里需要根据实际情况使用合适的签名算法
        $paramPattern = 'app_key'.$appKey.'method'.'product.getCategories'.'param_json'.'{cid:12,page:1}'.'timestamp'.'2018-06-19 16:06:59'.'v'.'2';
        $signPattern = $appSecret.$paramPattern.$appSecret;
        $sign = hash_hmac("sha256", $signPattern, $appSecret);
        $params['sign'] = $sign;
        $params['store_id'] = $store_id;
        // 构造请求 URL
        $requestUrl = 'https://openapi-fxg.jinritemai.com/shop/getStoreDetail?' . http_build_query($params);
        // 发送请求
        $response = file_get_contents($requestUrl);
        // 处理响应
        if ($response !== false) {
            $responseData = json_decode($response, true);
            if ($responseData) {
                // 处理 API 响应数据
                return $responseData;
            } else {
                $this->error('响应中的无效JSON');
            }
        } else {
            $this->error('发送请求错误');
        }
    }

    //要的商品
    public function ddss_list()
    {
        //curl版
        // 替换为你的实际应用密钥和访问令牌
        $appKey = $this->request->param('appKey');
        $accessToken = $this->request->param('accessToken');
        $appSecret = $this->request->param('appSecret');

        // 构造请求参数
        $params = [
            'app_key' => $appKey,                        // 应用密钥
            'method' => '',                              // API 方法，需要根据实际情况填写
            'access_token' => $accessToken,              // 访问令牌
            'param_json' => '{}',                        // 请求参数的 JSON 字符串，这里为空对象 {}
            'timestamp' => '2018-06-19 16:06:59',       // 时间戳，表示请求的时间
            'v' => '2',                                  // API 版本
        ];

        // 生成签名，需要根据实际情况使用合适的签名算法
        $paramPattern = 'app_key'.$appKey.'method'.'product.getCategories'.'param_json'.'{cid:12,page:1}'.'timestamp'.'2018-06-19 16:06:59'.'v'.'2';
        $signPattern = $appSecret.$paramPattern.$appSecret;
        $sign = hash_hmac("sha256", $signPattern, $appSecret);
        $params['sign'] = $sign;

        // 构造请求 URL
        $requestUrl = 'https://openapi-fxg.jinritemai.com?' . http_build_query($params);

        // 发送请求
        $response = file_get_contents($requestUrl);

        // 处理响应
        if ($response !== false) {
            $responseData = json_decode($response, true);
            if ($responseData) {
                // 处理 API 响应数据
                $data_dd = [];
                foreach ($responseData['data'] as $item)
                {
                    //详情
                    $products_detail_info = $this->products_detail_info($item['product_id'],$appKey,$accessToken,$appSecret);
                    $freightTemplate = $this->yunfei_info($products_detail_info['freight_id'],$appKey,$accessToken,$appSecret);
                    //门店
                    $store = $this->store_info($item['store_id'],$appKey,$accessToken,$appSecret);
                    $goods_pdds_value = [];
                    //商品编码
                    $goods_pdds_value['goods_id'] = $item['product_id'];
                    //商品主图
                    $goods_pdds_value['image_url'] = $item['img'];
                    //标题
                    $goods_pdds_value['title'] = $item['name'];
                    //商品总销量
                    $goods_pdds_value['sales_num'] = $item['sell_num'];
                    //价格
                    $market_price = $products_detail_info['market_price'];
                    $market_price = bcmul($market_price,0.01,2);
                    $goods_pdds_value['price'] = $market_price;
                    //劵后价
                    $discount_price = $products_detail_info['discount_price'];
                    $discount_price = bcmul($discount_price,0.01,2);
                    $goods_pdds_value['coupons_price'] = $discount_price;
                    //总评价*
                    $goods_pdds_value['evaluation'] = 0.00;
                    //24小时销量*
                    $goods_pdds_value['sales24_num'] = 0;
                    //运费
                    $freightTemplate_price = $freightTemplate['fixed_amount'];
                    $freightTemplate_price = bcmul($freightTemplate_price,0.01,2);
                    $goods_pdds_value['freight'] = $freightTemplate_price;
                    //好评率*
                    $goods_pdds_value['positive_review_rate'] = $item['goods_id'];
                    //上架时间
                    $goods_pdds_value['listing_time'] = $item['create_time'];
//                    //店铺名称*
                    $goods_pdds_value['shop_name'] = $store['store_detail']['poi_audit_info']['name'];
//                    //店铺商品数*
//                    $goods_pdds_value['shop_goods_num'] = $item['goods_id'];
//                    //店铺评分*
//                    $goods_pdds_value['shop_rating'] = $item['goods_id'];
                    //分类
                    $goods_pdds_value['cate1_id'] = $item['category_detail']['first_cid'];
                    $goods_pdds_value['cate2_id'] = $item['category_detail']['second_cid'];
                    $goods_pdds_value['cate3_id'] = $item['category_detail']['third_cid'];
                    $goods_pdds_value['cate4_id'] = $item['category_detail']['fourth_cid'];
                    $data_dd[] = $goods_pdds_value;
                }
                Db::startTrans();
                try {
                    Db::name('ddss')->insertAll($data_dd);
                    // 如果所有操作都成功，提交事务
                    Db::commit();
                }catch (Exception $e){
                    // 如果有任何一个操作失败，回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }

            } else {
                $this->error('响应中的无效JSON');
            }
        } else {
            $this->error('发送请求错误');
        }
        $this->success('successful');
    }


    /**
     * 提供给前台
     */
    //商品列表
    public function get_pdd_list()
    {
        $goods_field = "id,goods_id,image_url,title,sales_num,price,coupons_price,
        evaluation,sales24_num,freight,positive_review_rate,listing_time,shop_name,
        shop_goods_num,shop_rating,cate1_id";
//        ,cate2_id,cate3_id,cate4_id";
        $pddss = Db::name('pddss')->field($goods_field)->paginate();
        $cate_list = Db::name('pdd_cate')->field("id,cat_id,cat_name")->where('leaf',1)->select();
        $rows = $pddss->items();
        foreach ($rows as &$pddss_item){
            foreach ($cate_list as $cate_item){
                if ($pddss_item['cate1_id'] == $cate_item['cat_id']){
                    $pddss_item['cate1_name'] = $cate_item['cat_name'];
                }
            }
        }
        $result = [
            'total' => $pddss->total(),
            'per_page' => $pddss->listRows(),
            'current_page' => $pddss->currentPage(),
            'last_page' => $pddss->lastPage(),
            'data' => $rows
        ];
        $this->success('successful',$result);
    }






}
